<?php
namespace App\Http\Controllers\Admin;

use App\Services\Admin\FuwuService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;

class FuwuController extends BaseController
{
    //服务

    public function __construct(FuwuService $service)
    {
        $this->db = $service;
    }

    /**
     * 场景列表
     */
    public function getIndex(Request $request)
    {
        $pages['start'] = $request->post('pageStart', 0);
        $pages['limit'] = $request->post('pageLimit', 10);
        $pas['type'] = $request->post('type', 0);
        $res = $this->db->getIndex($pages, $pas);
        if ($res['code']!=0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //场景修改
    public function modify(Request $request)
    {
        //字段验证
        $this->validate($request, [
            'id' => 'required',
            'title' => 'required|min:2|max:255',
        ], [
            'id.required' => '场景ID必须的',
            'title.required' => '场景名称必须的',
            'title.min' => '场景名称不能少于 :min 字符',
            'title.max' => '场景名称不能多于 :max 字符',
        ]);
        $id = $request->post('id', 0);
        $pas['title'] = $request->post('title', '');
        $pas['type'] = $request->post('type', 0);
        $pas['price'] = $request->post('price', 0);
        $pas['gsprice'] = $request->post('gsprice', 0);
        $pas['cnt'] = $request->post('cnt', '');
        $thumb = $request->post('thumb', '');
        $pas['price'] *= 100;
        $pas['gsprice'] *= 100;
        if ($thumb && substr($thumb, 0, 5) == 'data:') {
            $pas['thumb'] = Upload::getPathByBase64($thumb);
        }
        if ($id) {
            $res = $this->db->modify($id, $pas);
        } else {
            $res = $this->db->add($pas);
        }
        if ($res['code']!=0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //场景删除
    public function del(Request $request)
    {
        //字段验证
        $this->validate($request, [
            'id' => 'required',
        ], [
            'id.required' => '场景ID必须的',
        ]);
        $id = $request->post('id', 0);
        $res = $this->db->del($id);
        if ($res['code']!=0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    /**
     * 家政日期
     */
    public function jiazhengDay(Request $request)
    {
        if (env('APP_ENV') == 'test') {
            $this->db->jiazhengInput(); //图片数据入库
        }
        $pages['start'] = $request->post('pageStart', 1);
        $pages['limit'] = $request->post('pageLimit', 10);
        $res = $this->db->jiazhengDay($pages);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    /**
     * 家政图片
     */
    public function jiazhengImg(Request $request)
    {
        $day = $request->post('day', '');
        $pages['start'] = $request->post('pageStart', 1);
        $pages['limit'] = $request->post('pageLimit', 10);
        if (!$day) {
            return $this->toJson(-2, '参数错误');
        }
        $res = $this->db->jiazhengImg($pages, $day);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    /**
     * 重置图片宽高==>>要手动操作
     */
    public function resetSize(Request $request)
    {
        $day = $request->get('day', '');
        if (!$day) {
            return '日期错误';
        }
        $targetWidth = 360;  // 目标宽度
        //$targetHeight = 480; // 目标高度
        $inputDir = 'upload/jiazheng-bak/'.$day;
        $outputDir = 'upload/jiazheng/'.$day;
        // 确保输出目录存在
        if (!file_exists($outputDir)) {
            mkdir($outputDir, 0777, true);
        }
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $files = scandir($inputDir);
        foreach ($files as $file) {
            if (!in_array($file, ['.', '..'])) {
                $filePath = $inputDir . '/' . $file;
                $fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
                echo $filePath; echo '<br>';
                $imgSize = getimagesize($filePath);
                $irate = $imgSize[1] / $imgSize[0];
                $targetHeight = $targetWidth * $irate;
                //var_dump($imgSize); echo '<br>';
                // 检查文件是否为图片
                if (in_array($fileExtension, $allowedExtensions)) {
                    // 根据文件类型创建图像资源
                    switch ($fileExtension) {
                        case 'jpg':
                        case 'jpeg':
                            $image = imagecreatefromjpeg($filePath);
                            break;
                        case 'png':
                            $image = imagecreatefrompng($filePath);
                            break;
                        case 'gif':
                            $image = imagecreatefromgif($filePath);
                            break;
                        default:
                            continue 2; // 跳过不支持的文件
                    }
                    // 获取原始图片的宽高
                    $originalWidth = imagesx($image);
                    $originalHeight = imagesy($image);
                    // 创建目标尺寸的画布
                    $resizedImage = imagecreatetruecolor($targetWidth, $targetHeight);
                    // 调整图片大小
                    imagecopyresampled(
                        $resizedImage, // 目标图像
                        $image,        // 原始图像
                        0, 0,          // 目标图像的起始坐标
                        0, 0,          // 原始图像的起始坐标
                        $targetWidth,  // 目标宽度
                        $targetHeight, // 目标高度
                        $originalWidth, // 原始宽度
                        $originalHeight // 原始高度
                    );
                    // 保存调整后的图片
                    $outputPath = $outputDir . '/' . $file;
                    switch ($fileExtension) {
                        case 'jpg':
                        case 'jpeg':
                            imagejpeg($resizedImage, $outputPath, 90); // 90% 质量
                            break;
                        case 'png':
                            imagepng($resizedImage, $outputPath, 9); // 9 压缩级别
                            break;
                        case 'gif':
                            imagegif($resizedImage, $outputPath);
                            break;
                    }
                    // 释放内存
                    imagedestroy($image);
                    imagedestroy($resizedImage);
                    echo "Resized and saved: $file\n";
                    echo '<br>';
                }
            }
        }
    }

    //配置文件
    protected $config = 'config.json';

    //配置获取
    public function configOne(Request $request)
    {
        $configs = file_get_contents($this->config);
        $configs = json_decode($configs, true);
        if (isset($configs['xcx']['iswx'])) {
            $wx = $configs['xcx']['iswx'];
        } else {
            $wx = 0;
        }
        return $this->toJson(0, '', ['iswx' => $wx]);
    }

    //配置设置
    public function configModify(Request $request)
    {
        $iswx = $request->post('iswx', 0);
        $configs = file_get_contents($this->config);
        $configs = json_decode($configs, true);
        $configs['xcx']['iswx'] = $iswx;
        file_put_contents($this->config, json_encode($configs, 384));
        return $this->toJson();
    }
}